<template>
    <div class="login-container">
      <el-card class="login-card">
        <template #header>
          <div class="card-header">
            <h2>客户订购系统</h2>
          </div>
        </template>
        <el-form
          :model="form"
          :rules="rules"
          ref="formRef"
          label-width="80px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="form.password" type="password" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="login" style="width: 100%">登录</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </template>
  
  <script setup>
  import { reactive, ref } from 'vue'
  import { ElMessage } from 'element-plus'
  import { useRouter } from 'vue-router'
  import axios from 'axios'
  
  const router = useRouter()
  const formRef = ref(null)
  
  const form = reactive({
    username: '',
    password: ''
  })
  
  const rules = reactive({
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 5, message: '用户名长度不能小于5位', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
    ]
  })
  
  const login = async () => {
    if (!formRef.value) return
  
    try {
      // 先验证表单
      await formRef.value.validate()
  
      // 表单验证通过后，发送登录请求
      const params = new URLSearchParams()
      params.append('username', form.username)
      params.append('password', form.password)
      const res = await axios.post('http://localhost:8080/admin/login', params)
      if (res.data.code === 200) {
        localStorage.setItem('admin', JSON.stringify(res.data.data))
        ElMessage.success('登录成功')
        router.push('/product')
      } else {
        ElMessage.error(res.data.message)
      }
    } catch (error) {
      // 如果是表单验证错误，不显示任何提示（因为表单会自动显示验证错误）
      if (!error.message?.includes('validate')) {
        // ElMessage.error('登录失败')
      }
    }
  }
  </script>
  
  <style scoped>
  .login-container {
    height: 100%;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f0f2f5;
    position: fixed;
    top: 0;
    left: 0;
  }
  
  .login-card {
    width: 400px;
    border-radius: 8px;
  }
  
  .card-header {
    text-align: center;
  }
  
  :deep(.el-card__header) {
    padding: 20px;
  }
  
  :deep(.el-card__body) {
    padding: 30px 40px;
  }
  </style>
  